#!/usr/bin/env python
#encoding=utf-8

import urllib
import urllib2
import cookielib
import time
import StringIO
import gzip

# APIs
POST_URL = 'http://www.laiwang.com/stream/add.json'
LIST_URL = 'http://www.laiwang.com/api/v1/message/conversation/list?offset=%d&size=%d&_=%d'

def _http_request(url, data=None, headers=[], cookie=None):
    if cookie == None:
        # TODO: load cookie from file
        cookie = '__LWMQTT_FINGER_PRINT__=vQOJ6BYg; JSESSIONID=K9M86CB1-KYHK2HF6KKGFFK3ITISY1-P9CPLMNH-0B5; setmp=hBH1PddcvWo%3D; __last_loginid__=1179910; longtermCookie=hBH1PddcvWo%3D; tmp0=eNpdkE1Lw0AYhOsPUPTgTVB6tYXdd797bG1N2KYtRIR6CZv9qEGjNkkxKt71X9taT54GhmeYYaLjPH%2FMjLW%2BrrPm%2BcE%2FnVswAjiVzjCTM6Go89QxwBgoOId%2FA%2FUmL4tmH0AX3FqGHbeUKo4QZoEH63MssTTCUyHP%2Fndkvn0pKp81Remnnc7B8PLbfB3tKFtXYc%2Bcrt9GbWpXr%2FMyXr2vzW3b6qQ%2BTMdpGs9nWTK%2FGk%2FR8qNwg65WieSjIe7rZaQhmnCtrycTTeKbOF3i%2FkKNFtNkFvXRkHV7thlgIgkHQhWhAvWM3RtESQAsSK9sB%2BjzZLem8qHy9f3fMeAUhJBvUaEMgNiKQEqaYCVDzN%2F9AGL%2BZbE%3D'
    # compse opener
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    newheaders = [
        ('User-agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36'),
        ('Accept', 'application/json, text/javascript, */*; q=0.01'),
        ('Accept-Encoding', 'gzip,deflate,sdch'),
        ('Accept-Language', 'en-US,en;q=0.8,zh-CN;q=0.6'),
        ('Connnection', 'keep-alive'),
        ('Host', 'www.laiwang.com'),
        ('Origin', 'http://www.laiwang.com'),
        ('PV', 'false'),
        ('Cookie', cookie),
        ]
    for h in headers:
        newheaders.append(h)
    opener.addheaders = newheaders
    urllib2.install_opener(opener)
    if data == None:
        req = urllib2.Request(url=url)
    else:
        req = urllib2.Request(url=url, data=urllib.urlencode(data))
    resp = urllib2.urlopen(req)
    obj = ''
    if resp.info().get('Content-Encoding') == 'gzip':
        buf = StringIO.StringIO(resp.read())
        f = gzip.GzipFile(fileobj=buf)
        obj = f.read()
    else:
        obj = resp.read()
    return obj

def _now_sec():
    return long(time.time()*1000)

def init():
    # get login cookie
    pass

def get_list(offset=0, size=30):
    url = LIST_URL%(offset, size, _now_sec())
    headers = [('Authorization', 'Bearer c2a72648da5ab5794de4d5211242dd1')]
    resp = _http_request(url=url, headers=headers)
    print resp

def post_msg(msg):
    url = POST_URL
    data = {
        'content':msg,
        'onlyFriends':'Y',
        'enentId':'',
        'csrf_token':'qyCxScgwOmIgzqaVxxKMs'
    }
    headers = [
        ('Content-Length', '254'),
        ('Content-Type', 'application/x-www-form-urlencoded'),
        ('Cache-Control', 'max-age=0'),
        ('Referer', 'http://www.laiwang.com/home'),
        ('X-Requested-With', 'XMLHttpRequest'),
    ]
    resp = _http_request(url=url, data=data, headers=headers)
    print resp

if __name__ == '__main__':
    get_list(0, 1)
    post_msg('hello laiwang.')

